package com.unhz.taigu.controller;

import com.unhz.generator.enums.EnumStatus;
import com.unhz.generator.enums.EnumValid;
import com.unhz.generator.pojo.AreaDict;
import com.unhz.generator.pojo.InsoleImage;
import com.unhz.generator.pojo.SysUser;
import com.unhz.generator.pojo.User;
import com.unhz.generator.utils.*;
import com.unhz.generator.utils.service.FileUtilService;
import com.unhz.generator.vo.UserVo;
import com.unhz.taigu.service.AreaDictService;
import com.unhz.taigu.service.InsoleImageService;
import com.unhz.taigu.service.SysUserService;
import com.unhz.taigu.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author: 王林恩
 * @Description:
 * @Date: Created in 下午 2:15 2018/1/30 0030
 * @Modified By:
 */
@Controller
@RequestMapping("/fileController")
public class FileController {


/*    @Autowired
    private FileUtilService fileUtilService;
    @Autowired
    private InsoleImageService insoleImageService;
    @Autowired
    private AreaDictService areaDictService;
    *//**
     * 用户业务层
     **//*
    @Autowired
    private SysUserService sysUserService;*/
    @Autowired
    private UserService userService;
/*
    @RequestMapping("/uploadUserHeadImg")
    public void uploadUserHeadImg(@RequestParam("filename")MultipartFile file, HttpServletRequest request,
                                  HttpServletResponse response) throws IOException {
        String path = request.getSession().getServletContext().getRealPath("upload");
        //String path = "http://47.96.250.168/file_img/headimage";
        String targetname = fileUtilService.upload(file,path);
       // response.getWriter().print(insoleImageService.selectOne().getFilePath()+"/"+targetname);
        //修改返回测试
        // response.getWriter().print(CommonFileAddress.FilePath+"/"+targetname);
    }*/





    //导出excle
    @RequestMapping("/outExcel")
    public void outExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User) request.getSession().getAttribute("user");
        //logService.insertMyBtLog("用户信息导出", "执行了用户信息导出信息", user.getUserName());

        //1.查询所有需要的数据
        List<UserVo> userVoList = userService.findAllUser("");//参数是管理员名称
        //2.使用POI将数据写进excel表中
        //2.1在内存中创建一个excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2.2创建一个标签页
        HSSFSheet sheet = workbook.createSheet("用户列表");
        //2.3创建标题行
        HSSFRow headRow = sheet.createRow(0);
        headRow.createCell(0).setCellValue("用户id");
        headRow.createCell(1).setCellValue("真实姓名");
        headRow.createCell(2).setCellValue("手机号码");
        headRow.createCell(3).setCellValue("岗位：采购员 设计师");
        headRow.createCell(4).setCellValue("QQ");
        headRow.createCell(5).setCellValue("企业名称");
        headRow.createCell(6).setCellValue("企业详细地址");
        headRow.createCell(7).setCellValue("企业仓库详细地址");
        headRow.createCell(8).setCellValue("所属管理员");
        headRow.createCell(9).setCellValue("审核状态");
        headRow.createCell(10).setCellValue("状态");
        //2.4将需要的数据放入excel表中
        for (UserVo u : userVoList) {
            String companyProvince = u.getCompanyProvince();
            String companyCity = u.getCompanyCity();
            String companyCounties = u.getCompanyCounties();
            String companyAddress = u.getCompanyAddress();

            String StorageProvince = u.getStorageProvince();
            String StorageCity = u.getStorageCity();
            String StorageCounties = u.getStorageCounties();
            String StorageAddress = u.getStorageAddress();
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            dataRow.createCell(0).setCellValue(u.getId());
            dataRow.createCell(1).setCellValue(u.getUserName());
            dataRow.createCell(2).setCellValue(u.getUserPhone());
            dataRow.createCell(3).setCellValue(u.getJob());
            dataRow.createCell(4).setCellValue(u.getQq());
            dataRow.createCell(5).setCellValue(u.getCompanyName());
            dataRow.createCell(6).setCellValue(companyProvince+companyCity+companyCounties+companyAddress);
            dataRow.createCell(7).setCellValue(StorageProvince+StorageCity+StorageCounties+StorageAddress);
            dataRow.createCell(8).setCellValue(u.getAdminId());
            if (String.valueOf(EnumStatus.CHECKING.getIndex()).equals(u.getStatus())){
                dataRow.createCell(9).setCellValue("审核中");
            }
            if (String.valueOf(EnumStatus.PASS.getIndex()).equals(u.getStatus())){
                dataRow.createCell(9).setCellValue("审核通过");
            }
            if (String.valueOf(EnumStatus.FAIL.getIndex()).equals(u.getStatus())){
                dataRow.createCell(9).setCellValue("审核不通过");
            }
            if (String.valueOf(EnumValid.DISABLE.getIndex()).equals(u.getValid())){
                dataRow.createCell(10).setCellValue("禁用");
            }
            if (String.valueOf(EnumValid.ENABLED.getIndex()).equals(u.getValid())){
                dataRow.createCell(10).setCellValue("启用");
            }
            if (String.valueOf(EnumValid.FIRST_ENABLED.getIndex()).equals(u.getValid())){
                dataRow.createCell(10).setCellValue("第一次出现启用的状态");
            }

        }
        //3.输出流进行文件下载
        String filename = "用户列表信息.xls";
        String mimeType = request.getSession().getServletContext().getMimeType(filename);
        ServletOutputStream outputStream = response.getOutputStream();


        //获取客户端的浏览器类型
        String agent = request.getHeader("User-Agent");
        filename = FileUtils.encodeDownloadFilename(filename, agent);
        response.setHeader("Content-disposition", "attachment; filename=" + filename);
        workbook.write(outputStream);
    }

    //导入信息

    /**
     * 描述：通过传统方式form表单提交方式导入excel文件JSON上传
     *
     * @param request
     * @throws Exception
     */
/*    @RequestMapping("/inExcel")
    @ResponseBody
    public JsonResult inExcel(HttpServletRequest request) throws Exception {
        //User user = (User) request.getSession().getAttribute("user");
        //logService.insertMyBtLog("用户信息导入", "执行了用户信息导入信息", user.getUserName());

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String status = "";
        InputStream in = null;
        List<List<Object>> listob = null;
        MultipartFile file = multipartRequest.getFile("upfile");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }

        String fileNames = file.getOriginalFilename();
        String fileFormat = fileNames.substring(fileNames.lastIndexOf("."),fileNames.length());
        if (!(".xls".equals(fileFormat))){
            return JsonResult.failure("文件类型错误，请导入后缀为.xls的文件");
        }
        in = file.getInputStream();
        listob = new ImportExcelUtil().getBankListByExcel(in, file.getOriginalFilename());
        in.close();
        //该处可调用service相应方法进行数据保存到数据库中，现只对数据输出
        for (int i = 0; i < listob.size(); i++) {
             List<Object> lo = listob.get(i);
            UserVo vo = new UserVo();
            vo.setId(String.valueOf(lo.get(0)));
            SysUser sysUser = sysUserService.selectByUserName(String.valueOf(lo.get(1)));
            if (sysUser!=null){
                vo.setAdminId(String.valueOf(sysUser.getId()));
            }
            vo.setUserPhone(String.valueOf(lo.get(2)));
            vo.setUserName(String.valueOf(lo.get(3)));
            vo.setJob(String.valueOf(lo.get(4)));
            vo.setQq(String.valueOf(lo.get(5)));
            vo.setCompanyName(String.valueOf(lo.get(6)));
            vo.setStatus(String.valueOf(lo.get(7)));

            User u = new User();

            u.setAdminId(Integer.parseInt(vo.getAdminId()));
            if (vo.getUserName()!=null){
                u.setUserName(vo.getUserName());
            }
            if (vo.getUserPhone()!=null){
                u.setUserPhone(vo.getUserPhone());
            }

            *//*if ("启用".equals(vo.getJob())){
                u.setJob(Integer.parseInt(vo.getJob()));
            }else if ("禁用".equals(vo.getJob())){
                u.setJob(Integer.parseInt(vo.getJob()));
            }else {
                u.setJob(Integer.parseInt(vo.getJob()));
            }*//*
            if (vo.getQq()!=null){
                u.setQq(vo.getQq());
            }
            if (vo.getCompanyName()!=null){
                u.setCompanyName(vo.getCompanyName());
            }
            if ("启用".equals(vo.getStatus())){
                u.setStatus(1);
            }else if ("禁用".equals(vo.getStatus())){
                u.setStatus(2);
            }else {
                u.setStatus(3);
            }

            //如果用户名存在怎么处理
            //查询用户名
            UserVo userVo = userService.findUser(vo.getUserName());
            if (userVo!=null){
                continue;
            }

            int res = userService.insert(u);
            if (res>0){
                status = "success";
            }
        }
        if (status.equals("success")) {
            //导入成功
            return JsonResult.success("导入数据成功");
        }
        return JsonResult.failure("excle导入数据失败");
    }*/



/*    *//**
     * 文件上传功能
     * @param file
     * @return
     * @throws IOException
     *//*
    @RequestMapping(value="/upload")
    @ResponseBody
    public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
        String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
        String fileName = file.getOriginalFilename();
        if ("".equals(fileName)){
            return "请选择上传图片！";
        }
        File dir = new File(path,fileName);
        String fileNames = file.getOriginalFilename();
        //String fileName2 = fileNames.substring(0,fileNames.lastIndexOf("."));
        //String fileFormat = fileNames.substring(fileNames.lastIndexOf("."),fileNames.length());
        if(!dir.exists()){
            dir.mkdirs();
        }
        //MultipartFile自带的解析方法
        file.transferTo(dir);
        InsoleImage insoleImage = new InsoleImage();
        insoleImage.setImageUrl(CommonFileAddress.FilePath+"/"+fileNames);
        insoleImage.setInsoleId(1);


        int res = insoleImageService.addInsoleImage(insoleImage);
        return "//////////////////////ok!";
    }*/

/*    *//**
     * 文件下载功能
     * @param request
     * @param response
     * @throws Exception
     *//*
    @RequestMapping("/down")
    public void down(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //模拟文件，myfile.txt为需要下载的文件1.获取要下载的文件的绝对路径
        String fileName = request.getSession().getServletContext().getRealPath("upload")+"/myfile.txt";
        //获取输入流
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
        //假如以中文名下载的话
        String filename = "下载文件.txt";
        //转码，免得文件名中文乱码
        filename = URLEncoder.encode(filename,"UTF-8");
        //设置Content-Disposition响应头控制浏览器以下载的形式打开文件
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while((len = bis.read()) != -1){
            //使用OutputStream将数据输出到客户端浏览器
            out.write(len);
            out.flush();
        }
        out.close();
    }*/

   /* @RequestMapping("/download")
    public String download(String filePath, HttpServletRequest request,
                           HttpServletResponse response) {
        try {
　　　　　　　　　　//获取文件名
            String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
            System.out.println(filePath);
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
　　　　　　　　　　//处理下载弹出框名字的编码问题
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
　　　　　　　　　　//获取文件的下载路径
            String path = request.getSession().getServletContext().getRealPath(filePath);
            System.out.println(path);
　　　　　　　　　　//利用输入输出流对文件进行下载
            InputStream inputStream = new FileInputStream(new File(path));

            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            // 这里主要关闭。
            os.close();

            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //  返回值要注意，要不然就出现下面这句错误！
        //java+getOutputStream() has already been called for this response
        return null;
    }
*/







}
